package admin.sys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.common.CacheManager;
import com.common.CommonUtil;
import com.common.EmiJsonObj;
import com.common.MenuFun;
import com.common.ResultData;
import com.filter.BaseController;
import com.intercepter.AuthPassport;

import beans.sys.RoleModel;
import beans.sys.UserBean;
import service.sys.FunServiceImpl;
import service.sys.RoleFunServiceImpl;
import service.sys.RoleServiceImpl;
import service.sys.RoleUserServiceImpl;
import service.sys.UserServiceImpl;

@Controller
@RequestMapping("/role")
public class RoleController extends BaseController{
	@Resource
	private RoleServiceImpl roleServiceImpl;

	@Resource
	private FunServiceImpl funServiceImpl;

	@Resource
	private RoleFunServiceImpl rolefunServiceImpl;

	@Resource
	private RoleUserServiceImpl roleUserServiceImpl;

	@Resource
	private UserServiceImpl userServiceImpl;

	@RequestMapping("/index")
	@AuthPassport(actionName="index",controllerName="role")
	public String Index(){
		return "admin/sys/role/index";
	}

	@RequestMapping("/GetPageListJson")
	@ResponseBody
	@AuthPassport(actionName="index",controllerName="role")
	public void DataGrid(RoleModel model,String condition,String keyword){
		ResultData<List<Map>> rd = new ResultData<>();
		try{
			rd.setPage(model.getPage());
			if(!CommonUtil.isNullObject(condition)) {
				if(condition.equals("title"))model.setTitle(keyword);
			}
			List<Map> m = roleServiceImpl.queryByList(model);
			rd.setRows(m);
			rd.setRecords(model.getPager().getRowCount());
			rd.setTotal(model.getPager().getPageCount());
		}
		catch(Exception e){
			e.printStackTrace();
		}
		responseJson(rd);
	}

	@RequestMapping("/detail")
	@AuthPassport(actionName="index",controllerName="role")
	public String Detail(String id){
		if(!CommonUtil.isNullObject(id)){
			try {
				Map<String,Object> m = (Map<String,Object>)roleServiceImpl.queryById(id);
				getReq().setAttribute("id", m.get("id"));
				getReq().setAttribute("title", m.get("title"));
				if(m.containsKey("sort"))
					getReq().setAttribute("sort", m.get("sort"));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "admin/sys/role/detail";
	}

	@RequestMapping("/save")
	@ResponseBody
	@AuthPassport(actionName="index",controllerName="role")
	public void Save(String id,String title,Integer sort){
		ResultData<String> rd = new ResultData<>();
		Map<String,Object> m = new HashMap<>();
		m.put("title", title);
		m.put("sort", sort);
		if(sort==null)sort = 0;
		m.put("sort", sort);
		try {
			if(CommonUtil.isNullObject(id)){//新增
				m.put("id", UUID.randomUUID().toString());
				roleServiceImpl.add(m);
			}
			else{//编辑
				m.put("id", id);
				roleServiceImpl.update(m);
			}
			rd.setType(1);
		} catch (Exception e) {
			e.printStackTrace();
			rd.setType(3);
			rd.setMessage("保存失败");
		}
		CacheManager.clearAll("fun-");
		rd.setMessage("保存成功");
		responseJson(rd);
	}

	@RequestMapping("/del")
	@ResponseBody
	@AuthPassport(actionName="index",controllerName="role")
	public void Del(){
		String[] ids = getReq().getParameterValues("ids");
		try{
			roleServiceImpl.deletes(ids);
		}
		catch(Exception e){
			e.printStackTrace();
		}
		CacheManager.clearAll("fun-");
		ResultData<String> rd = new ResultData<>();
		rd.setType(1);
		rd.setMessage("删除成功");
		responseJson(rd);
	}

	@RequestMapping("/navi")
	@AuthPassport(actionName="index",controllerName="role")
	public String Navi(String id){
		getReq().setAttribute("roleid", id);
		return "admin/sys/role/rolefun";
	}

	@RequestMapping("/NaviRoleTree")
	@ResponseBody
	@AuthPassport(actionName="index",controllerName="role")
	public void NaviRoleTree(String roleId) {
		List<Map> listMenu = funServiceImpl.getAll("");//菜单
		List<Map> listRoleFun = rolefunServiceImpl.getByRoleid(roleId);

		List<Map> funTrees = new ArrayList<Map>();
		for(Object obj : listMenu){
			Map row = (Map) obj;
			if(!row.get("pid").toString().equals(""))continue;

			List<Map> childTrees = getChild(listMenu,listRoleFun,row.get("id").toString());
			if(childTrees.size()>0)row.put("hasChildren", true);
			else row.put("hasChildren", false);
			row.put("checkstate", checkHas(listRoleFun,row.get("id").toString(),"funid"));
			row.put("ChildNodes", childTrees);
			row.put("text", row.get("title"));
			row.put("img", row.get("iconCls"));
			row.put("value", row.get("id"));
			row.put("showcheck", true);
			row.put("isexpand", true);
			row.put("parentnodes", "");
			funTrees.add(row);
		}
		responseJsonArray(funTrees);
	}

	@RequestMapping("/navisave")
	@ResponseBody
	@AuthPassport(actionName="index",controllerName="role")
	public void navisave(String roleID){
		String[] ids = getReq().getParameter("ids").split(",");
		ResultData<String> rd = new ResultData<>();
		try{
			rolefunServiceImpl.saveRoleFun(roleID, ids);

			CacheManager.clearAll("fun-");
			rd.setType(1);
			rd.setMessage("保存成功!");
			responseJson(rd);
		}
		catch(Exception e){
			e.printStackTrace();
			rd.setType(1);
			rd.setMessage("保存失败!");
			responseJson(rd);
		}
	}

	public List<Map> getChild(List<Map> rows,List<Map> listRoleFun,String id){
		List<Map> menuTrees = new ArrayList<Map>();
		for(Object obj : rows) {
			Map row = (Map) obj;
			if(!row.get("pid").toString().equals(id))continue;
			List<Map> childTrees = getChild(rows,listRoleFun,row.get("id").toString());
			if(childTrees.size()>0)row.put("hasChildren", true);
			else row.put("hasChildren", false);
			row.put("checkstate", checkHas(listRoleFun,row.get("id").toString(),"funid"));
			row.put("ChildNodes", childTrees);
			row.put("text", row.get("title"));
			row.put("img", row.get("iconCls"));
			row.put("value", row.get("id"));
			row.put("showcheck", true);
			row.put("isexpand", true);
			row.put("parentnodes", id);
			menuTrees.add(row);
		}
		return menuTrees;
	}

	private int checkHas(List<Map> list,String menuid,String field){
		int bo = 0;
		for(Object obj : list){
			Map row = (Map) obj;
			if(row.get(field).toString().equals(menuid)){
				bo = 1;
				break;
			}
		}
		return bo;
	}

	@RequestMapping("/user")
	@AuthPassport(actionName="index",controllerName="role")
	public String User(String id) throws Exception{
		List<UserBean> listMenu = userServiceImpl.getAll();//用户
		List<Map> listRoleFun = roleUserServiceImpl.getByRoleid(id);

		List<Map> funTrees = new ArrayList<Map>();
		for(UserBean obj : listMenu){
			Map row = new HashMap();
			row.put("userid", obj.getId());
			row.put("job", obj.getJob());
			row.put("checked", checkHas(listRoleFun,row.get("userid").toString(),"userid"));
			if(CommonUtil.isNullObject(obj.getUsername()))
				row.put("username", "");
			else	
				row.put("username", obj.getUsername());
			row.put("account", obj.getAccount());
			funTrees.add(row);
		}
		getReq().setAttribute("roleid", id);
		getReq().setAttribute("funTrees", EmiJsonObj.fromArray(funTrees).toString());
		return "admin/sys/role/roleuser";
	}


	@RequestMapping("/usersave")
	@ResponseBody
	@AuthPassport(actionName="index",controllerName="role")
	public void Usersave(String roleID,String ids){
		String[] idsInfo = ids.split(",");
		roleUserServiceImpl.saveRoleFun(roleID, idsInfo);

		CacheManager.clearAll("fun-");
		ResultData<String> rd = new ResultData<>();
		rd.setType(1);
		rd.setMessage("保存成功");
		responseJson(rd);
	}
}
